from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, desc, func
from sqlalchemy.orm import relationship
from .base import Base, db
from flask import current_app
from app.spider.ys_book import YsBook


class Gift(Base):
    id = Column(Integer, primary_key=True)
    user = relationship('User')
    uid = Column(Integer, ForeignKey('user.id'))
    isbn = Column(String(15), nullable=False)
    # book = relationship('Book')
    # bid = Column(Integer, ForeignKey('user.id'))
    launched = Column(Boolean, default=False, comment='是否已经赠送：0 否，1 是')

    @classmethod
    def recent(cls):
        """
        最新赠送的书籍
        :return:
        """
        gifts = cls.query.filter_by(launched=False).group_by(cls.isbn).order_by(desc(cls.create_time)).limit(
            current_app.config['RECENT_BOOK_COUNT']).distinct().all()
        return gifts

    @property
    def book(self):
        """
        赠送对应的书籍
        :return:
        """
        ys_book = YsBook()
        ys_book.search_by_isbn(self.isbn)
        return ys_book.first

    @classmethod
    def get_user_gifts(cls, uid):
        """
        用户已上传书籍的赠送清单
        :param uid:
        :return:
        """
        gifts = cls.query.filter_by(uid=uid, launched=False).order_by(desc(cls.create_time)).all()
        return gifts

    @classmethod
    def get_wish_count(cls, isbn_list):
        """
        书籍的心愿数量统计
        :param isbn_list:
        :return:
        """
        from .wish import Wish
        count_list = db.session.query(func.count(Wish.id), Wish.isbn).filter(
            Wish.launched == False, Wish.isbn.in_(isbn_list), Wish.status == 1
        ).group_by(Wish.isbn).all()
        # 转换成列表
        count_list = [{'count': w[0], 'isbn': w[1]} for w in count_list]
        return count_list

    def is_yourself_gift(self, uid):
        """
        当前赠送书籍是否是用户自己的赠送的
        :param uid:
        :return:
        """
        return True if self.id == uid else False
